﻿<?php
class DbExecutor
{
    private static $_instance = null;
    private $_conn = null;
    private $_lastError = "";
    
    public function __construct()
    {
        $this->reconnect();
    }

    public function __destruct()
    {
        if ($this->_conn)
        {
            mysql_close($this->_conn);
        }
    }
    
    private function reconnect()
    {
        $this->_conn = mysql_connect(DB_HOST, DB_USER, DB_PWD);
        if (!$this->_conn)
        {
            write_log("connect db error");
            exit();
        }
        mysql_select_db(DB_NAME, $this->_conn);
    }
    
    public function getLastError()
    {
        return $this->_lastError;
    }
    
    public static function getInstance()
    {
        if(!self::$_instance)
        {
            self::$_instance = new DbExecutor();
        }
        return self::$_instance;
    }
    
	public function get($sql)
    {
        write_log("sql:" . $sql); 
        $r = mysql_query($sql, $this->_conn);
        if (false === $r)
        {
            $this->_lastError = mysql_errno($this->_conn);
            return false;
        }
        $return = array();
        while($row=mysql_fetch_array($r, MYSQL_ASSOC)) 
        {
            write_log("row:" . json_encode($row));
            $return[] = $row;
        }
        $c = count($return);
        
		return $c > 0 ? ($c==1 ? $return[0] : $return) : array();
    } 
	
	public function exec($sql)
	{
        write_log("sql:" . $sql); 
        $r = mysql_query($sql, $this->_conn);
        if (false === $r)
        {
            $this->_lastError = mysql_errno($this->_conn);
            return false;
        }
        return mysql_affected_rows();
	}
    
    public function insert($sql)
    {
        write_log("sql:" . $sql); 
        $r = mysql_query($sql, $this->_conn);
        if (false === $r)
        {
            $this->_lastError = mysql_errno($this->_conn);
            return false;
        }
        return mysql_insert_id();
    }
}
?>